/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CalcularEmprestimo.java
 *
 * Created on 11/12/2011, 15:49:25
 */

package gui;

import DAO.DAOGenerico;
import DAO.DAOJSON;
import empregado.Empregado;
import emprestimo.Emprestimo;
import emprestimo.EmprestimoService;
import exceptions.ValidacaoEmprestimoException;
import javax.swing.JOptionPane;
import validators.annotations.ValidateAnnotationParser;

/**
 *
 * @author Victor
 */
public class CalcularEmprestimo extends javax.swing.JDialog {
    private EmprestimoService emprestimoService;
    private DAOGenerico DAO;
    private Emprestimo emprestimo;
    private Empregado empregado;
    /** Creates new form CalcularEmprestimo */
    public CalcularEmprestimo(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        this.emprestimoService = new EmprestimoService();
        this.DAO = new DAOJSON();
        this.empregado = null;
        this.emprestimo = null;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cpfTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        emprestimoTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        prestacoesTextField = new javax.swing.JTextField();
        salvarEmprestimoButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        printNome = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        printEmprestimo = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        printPrestacao = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        printTotal = new javax.swing.JTextField();
        calcularButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Verdana", 0, 18));
        jLabel1.setForeground(new java.awt.Color(0, 102, 102));
        jLabel1.setText("Calcular Emprestimo");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel2.setForeground(new java.awt.Color(0, 51, 51));
        jLabel2.setText("CPF do empregado:");

        cpfTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cpfTextFieldActionPerformed(evt);
            }
        });
        cpfTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cpfTextFieldFocusGained(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel3.setForeground(new java.awt.Color(0, 51, 51));
        jLabel3.setText("Valor do empréstimo:");

        emprestimoTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                emprestimoTextFieldActionPerformed(evt);
            }
        });
        emprestimoTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                emprestimoTextFieldFocusGained(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel4.setForeground(new java.awt.Color(0, 51, 51));
        jLabel4.setText("Número de prestações:");

        prestacoesTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                prestacoesTextFieldActionPerformed(evt);
            }
        });
        prestacoesTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                prestacoesTextFieldFocusGained(evt);
            }
        });

        salvarEmprestimoButton.setText("Salvar Empréstimo");
        salvarEmprestimoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarEmprestimoButtonActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel5.setForeground(new java.awt.Color(0, 51, 51));
        jLabel5.setText("Nome:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel6.setForeground(new java.awt.Color(0, 51, 51));
        jLabel6.setText("Valor do Empréstimo:");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel7.setForeground(new java.awt.Color(0, 51, 51));
        jLabel7.setText("Valor de cada Prestação:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel8.setForeground(new java.awt.Color(0, 51, 51));
        jLabel8.setText("Valor total a pagar:");

        calcularButton.setText("Calcular");
        calcularButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calcularButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel1)
                .addContainerGap(285, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(calcularButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(printNome, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
                            .addComponent(printEmprestimo, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(salvarEmprestimoButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(prestacoesTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(printTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
                            .addComponent(printPrestacao, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cpfTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
                            .addComponent(emprestimoTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))))
                .addGap(33, 33, 33))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jLabel1)
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cpfTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(emprestimoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(prestacoesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(calcularButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(salvarEmprestimoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(108, 108, 108)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(printNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(printEmprestimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(printPrestacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(printTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cpfTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cpfTextFieldActionPerformed
        
}//GEN-LAST:event_cpfTextFieldActionPerformed

    private void cpfTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cpfTextFieldFocusGained
        cpfTextField.setText("");
}//GEN-LAST:event_cpfTextFieldFocusGained

    private void emprestimoTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emprestimoTextFieldActionPerformed

    }//GEN-LAST:event_emprestimoTextFieldActionPerformed

    private void emprestimoTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_emprestimoTextFieldFocusGained
        emprestimoTextField.setText("");
}//GEN-LAST:event_emprestimoTextFieldFocusGained

    private void prestacoesTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_prestacoesTextFieldActionPerformed
    }//GEN-LAST:event_prestacoesTextFieldActionPerformed

    private void prestacoesTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_prestacoesTextFieldFocusGained
        prestacoesTextField.setText("");
}//GEN-LAST:event_prestacoesTextFieldFocusGained
    /** Ao pressionar o botão, salva o empréstimo calculado no arquivo JSON
     */
    private void salvarEmprestimoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarEmprestimoButtonActionPerformed
        try{
            this.emprestimoService.fazerEmprestimo(this.empregado, this.emprestimo);
            JOptionPane.showMessageDialog(this, "Empréstimo salvo com sucesso");
        }catch(Exception e){
            JOptionPane.showMessageDialog(this, "Um erro foi encontrado "+e.getMessage());
        }
}//GEN-LAST:event_salvarEmprestimoButtonActionPerformed

    
/**
 * Valida os dados entrados pelo usuário. 
 * Caso não seja validado, lança exceção que será apresentada ao usuário por meio de uma janela de diálogo
*/
    
public void validarEntrada() throws NumberFormatException{
    try{
        int parseInt = Integer.parseInt(prestacoesTextField.getText());
    }catch(NumberFormatException nfe){
        //JOptionPane.showMessageDialog(this, "Um erro foi encontrado "+nfe.getMessage());
        throw new NumberFormatException("Número Prestações");
    }
    
    try{
        Double parseDouble = Double.parseDouble(emprestimoTextField.getText());
    }catch(NumberFormatException nfe){
        //JOptionPane.showMessageDialog(this, "Um erro foi encontrado "+nfe.getMessage());
        throw new NumberFormatException("Valor do Empréstimo");
    }
   
}
    /** Ao pressionar o botão, valida se os valores de entrada são números
      * e em caso positivo, calcula o empréstimo para o usuário com o CPF informado e suas preferencias
      * O calculo pode gerar um erro que será apresentado numa janela de diálogo
     */
private void calcularButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calcularButtonActionPerformed
   Empregado empregadoTemp = new Empregado();
   
   String cpf = cpfTextField.getText();
   empregadoTemp.setCpf(cpf);

   try{
        empregadoTemp = (Empregado) this.DAO.buscar(empregadoTemp);
   }catch(Exception e){
       System.out.println(e.getMessage());
   }
   
   try{
       this.validarEntrada();
       int prestacoes = Integer.parseInt(prestacoesTextField.getText());
       Double valorEmprestimo = Double.parseDouble(emprestimoTextField.getText());
       try{
            Emprestimo emprestimoTemp = this.emprestimoService.prepararEmprestimo(empregadoTemp, valorEmprestimo, prestacoes);
            this.empregado = empregadoTemp;
            this.emprestimo = emprestimoTemp;
            this.imprimirEmprestimoCalculado(emprestimo, empregado);
       }catch(ValidacaoEmprestimoException vee){
           JOptionPane.showMessageDialog(this, vee.getMessage(),"Erro", JOptionPane.ERROR_MESSAGE);
       }
   }catch(NumberFormatException nfe){
       JOptionPane.showMessageDialog(this,"Campo com número inválido: "+nfe.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
   }
}//GEN-LAST:event_calcularButtonActionPerformed
    /**
     * Imprime o resultado do cálculo por Empréstimo caso as verificações tenham tido sucesso
     * @param emprestimo    Empréstimo como foi calculado
     * @param empregado Empregado solicitante
    */
    private void imprimirEmprestimoCalculado(Emprestimo emprestimo, Empregado empregado){
        printNome.setText(empregado.getNome());
        printEmprestimo.setText(String.valueOf(emprestimo.getValorDesejado()));
        printPrestacao.setText(String.valueOf(emprestimo.getPrestacao()));
        printTotal.setText(String.valueOf(emprestimo.getNumPrestacoes() * emprestimo.getPrestacao()));
    }
    
    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CalcularEmprestimo dialog = new CalcularEmprestimo(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton calcularButton;
    private javax.swing.JTextField cpfTextField;
    private javax.swing.JTextField emprestimoTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField prestacoesTextField;
    private javax.swing.JTextField printEmprestimo;
    private javax.swing.JTextField printNome;
    private javax.swing.JTextField printPrestacao;
    private javax.swing.JTextField printTotal;
    private javax.swing.JButton salvarEmprestimoButton;
    // End of variables declaration//GEN-END:variables

}
